
#include "app_porting.h"

uint8_t short_string_fill(ShortString pdest, const uint8_t *psrc)
{
	if(NULL==pdest){
		return 0;
	}

	if(NULL==psrc){
		pdest[0]=0;
		return 1;
	}else{
		pdest[0]=strlen((const char *)psrc);
		strcpy((char *)&pdest[1],(const char *)psrc);
		pdest[pdest[0]+1]=0;
		return pdest[0]+1;
	}
}

int32_t short_string_cpy(ShortString dest, uint8_t dest_len, const ShortString src)
{
	//len+content+0
	if(src[0]+2>dest_len){
		return LS_FAIL;
	}
	
	dest[0]=src[0];
	if(src[0]>0){
		memcpy(&dest[1],&src[1],src[0]);
		dest[src[0]+1]=0;
	}
	return src[0]+1;
}

bool short_string_is_valid(ShortString pstr)
{
	if(NULL==pstr){
		return FALSE;
	}

	if(0==pstr[0]||0xff==pstr[0]){
		return FALSE;
	}

	if(0==pstr[pstr[0]+1]){
		return TRUE;
	}
		
	return FALSE;
}

uint8_t* short_string_strstr(ShortString str, const char *needle)
{
	if(FALSE==short_string_is_valid(str)){
		return NULL;
	}

	return (uint8_t*)strstr((const char*)&str[1],needle);
}

void short_string_content_len_get(ShortString str, char **pansi, uint8_t *plen)
{
	if(NULL!=pansi){
		*pansi=(char *)&str[1];
	}

	*plen=str[0];
}

uint8_t short_string_total_len_get(ShortString str)
{
	if(0==str[0]||0xff==str[0]){
		return 1;
	}

	return str[0]+1;
}
#ifdef TEST_ENABLE

#define SN_DEFAULT "SMB17000001"
#define TEST_BUF_LEN 100
uint8_t test_sn[TEST_BUF_LEN];
uint8_t dest_sn[TEST_BUF_LEN];

void short_string_test(void)
{
	uint8_t len;
	int32_t ret;
	uint8_t *p;
	ShortString psh;

	len=short_string_fill((ShortString)test_sn,SN_DEFAULT);
	debug_printf("len=%d,test_sn[0]=%d,data=%s\r\n",len,test_sn[0],&test_sn[1]);
	
	psh=(ShortString)dest_sn;	
	ret=short_string_cpy(psh,TEST_BUF_LEN,(ShortString)test_sn);
	debug_printf("ret=%d\r\n",ret);
	
	short_string_content_len_get(psh,(char**)&p,&len);
	debug_printf("len=%d,data=%s\r\n",len,p);

	p=short_string_strstr(psh,"17");
	debug_printf("strstr=%s\r\n",p);
	
	len=short_string_is_valid(psh);
	debug_printf("len=%d\r\n",len);
}
#endif

